package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.util.HashMap;

/**
 * @author fangy
 * @date 2022-09-03 22:29
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimail.product.controller")
public class GulimailExceptionControllerAdvice {


    @ExceptionHandler(value = WebExchangeBindException.class)
    public R handleVaildException(WebExchangeBindException e){

        log.error("数据校验出现问题：{},异常类型：{}",e.getMessage(),e.getClass());

        BindingResult result = e.getBindingResult();

        HashMap<String, String> errmap = new HashMap<>();

        result.getFieldErrors().forEach((item)->{
                //获取错误提示
                String message = item.getDefaultMessage();
                //获取错误的属性的名字
                String field = item.getField();

                errmap.put(field,message);
            });


        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",errmap);
    }



}
